import {
  PlusOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import { Button, Tag, Tooltip, Rate, message, Space } from 'antd';
import React, { useRef } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
  ProFormTextArea,
  ProFormRate,
} from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import moment from 'moment';
import { useRequest } from 'umi';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const editWeekPlanRef = useRef<ProFormInstance>();

  //新建任务
  const publishTask = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/publishTask`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //导师端——获取自己学生的周计划
  const getMyStuWeekPlan = useRequest((data = {}) => {
    let url = '';
    let count = 0;
    Object.keys(data).map((value: any, index: any) => {
      // console.log(value);
      let key_temp = value;
      let value_temp = data[value];
      if (data[value]) {
        if (count == 0) {
          url = url + '?' + key_temp + '=' + value_temp;
        } else {
          url = url + '&' + key_temp + '=' + value_temp;
        }
        count++;
      }
    });
    return {
      url: `http://10.1.40.84:9998/stuTrain/getMyStuWeekPlan` + url,
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
    };
  });

  //学生端——获取任务详细
  const getMyOneTask = useRequest(
    (id = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyOneTask?id=${id}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  //共通端——查看一个周计划详细
  const getOneWeekPlanState = useRequest(
    (id = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getOneWeekPlanState?id=${id}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  //修改周计划
  const updateWeekPlan = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/updateWeekPlan`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: () => {
        getMyStuWeekPlan.run();
        // getMyOverview.run();
      },
    },
  );
  const weekPlanColumns = [
    {
      title: '学生',
      dataIndex: 'stuName',
      key: 'stuName',
    },
    {
      title: '周计划名称',
      dataIndex: 'weekPlanName',
      key: 'weekPlanName',
    },
    {
      title: '所属阶段',
      dataIndex: 'stageName',
      key: 'stageName',
      render: (text: any) => <Tag color={'blue'}>{text}</Tag>,
    },
    {
      title: '周计划状态',
      dataIndex: 'weekPlanState',
      key: 'weekPlanState',
      render: (text: any) => {
        if (text === '未接收' || text === '忽略') {
          return (
            <Tag icon={<ClockCircleOutlined />} color="default">
              {text}
            </Tag>
          );
        } else if (text === '进行中') {
          return (
            <Tag icon={<SyncOutlined spin />} color={'processing'}>
              {text}
            </Tag>
          );
        } else {
          return (
            <Tag icon={<CheckCircleOutlined />} color="success">
              {text}
            </Tag>
          );
        }
      },
    },
    {
      title: '组长',
      dataIndex: 'seniorName',
      key: 'seniorName',
    },
    {
      title: '导师',
      dataIndex: 'teaName',
      key: 'teaName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: '操作',
      key: 'option',
      align: 'center',
      render: (text: any, record: any) => (
        <Space>
          <ModalForm
            key="1"
            title={'查看周计划'}
            trigger={
              <a
                onClick={() => {
                  getOneWeekPlanState.run(record?.id).then((e) => {
                    console.log(e);
                    editWeekPlanRef.current?.setFieldsValue(e);
                  });
                }}
              >
                查看
              </a>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
              destroyOnClose: true,
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              await waitTime(2000);
              console.log(values);
              updateWeekPlan.run(values);
              message.success('提交成功');
              return true;
            }}
            formRef={editWeekPlanRef}
          >
            <ProForm.Group>
              <ProFormText width="sm" name="id" hidden />
              <ProFormText width="sm" name="seniorId" hidden />
              <ProFormText width="sm" name="stageId" hidden />
              <ProFormText width="sm" name="studentId" hidden />
              <ProFormText width="sm" name="teacherId" hidden />
              <ProFormText
                width={'md'}
                name="weekPlanName"
                label="周计划名称"
                disabled
              />

              <ProFormSelect
                width={'md'}
                name="weekPlanState"
                label="周计划状态"
                valueEnum={{
                  未接收: '未接收',
                  忽略: '忽略',
                  进行中: '进行中',
                  已完成: '已完成',
                  负责人已审核: '负责人已审核',
                  导师已阅: '导师已阅',
                }}
              />

              <ProFormText
                width={'md'}
                name="personTarget"
                label="个人目标"
                disabled
              />
              <ProFormText
                width={'md'}
                name="teaTarget"
                label="导师规划目标"
                // disabled
              />
              <ProFormTextArea
                width={'md'}
                name="personEvaluate"
                label="个人评价"
                fieldProps={{
                  rows: 3,
                }}
                disabled
              />
              <ProFormTextArea
                width="md"
                name="teaEvaluate"
                label="导师评价"
                fieldProps={{
                  rows: 3,
                }}
              />
              <ProFormDatePicker
                width={'md'}
                name="createTime"
                label="创建时间"
                disabled
              />
              <ProFormRate
                // readonly
                width="md"
                name="teaScore"
                label="导师评分"
              />
            </ProForm.Group>
            <ProFormList
              name="materialList"
              label="材料信息"
              // rules={[
              //     {
              //         validator: async (_, value) => {
              //             // console.log(value);
              //             if (value && value.length > 0) {
              //                 return;
              //             }
              //             throw new Error('至少要有一项！');
              //         },
              //     },
              // ]}
              creatorButtonProps={{
                creatorButtonText: '添加材料',
                hidden: true,
              }}
              copyIconProps={false}
              deleteIconProps={false}
            >
              {(meta: any, index: any, action: any, count: any) => {
                return (
                  <ProFormGroup key="group">
                    <ProFormText
                      width="sm"
                      required
                      name="materialName"
                      label="材料名称"
                      disabled
                    />
                    <ProFormSelect
                      label="材料类型"
                      name="materialType"
                      width="xs"
                      required
                      disabled
                      valueEnum={{
                        学习报告: '学习报告',
                        参考文献: '参考文献',
                      }}
                    />
                    <ProFormDependency name={['materialType']}>
                      {({ materialType }) => {
                        if (materialType === '参考文献') {
                          return (
                            <ProFormText
                              width="sm"
                              name="materialContent"
                              label="文献链接"
                              required
                            />
                          );
                        } else if (
                          materialType === '学习报告' ||
                          materialType === '阶段性报告'
                        ) {
                          return (
                            <ProFormText
                              width="sm"
                              name="materialContent"
                              required
                              hidden
                            />
                          );
                        } else {
                          return null;
                        }
                      }}
                    </ProFormDependency>
                    <ProFormDependency name={['materialType']}>
                      {({ materialType }) => {
                        if (
                          materialType === '学习报告' &&
                          action.getCurrentRowData().materialContent
                        ) {
                          return (
                            <Button
                              type={'link'}
                              style={
                                index === 0
                                  ? { marginTop: 30 }
                                  : { marginTop: 0 }
                              }
                              onClick={() => {
                                window.open(
                                  action.getCurrentRowData().materialContent,
                                );
                              }}
                            >
                              下载
                            </Button>
                          );
                        } else {
                          return null;
                        }
                      }}
                    </ProFormDependency>
                  </ProFormGroup>
                );
              }}
            </ProFormList>
          </ModalForm>
        </Space>
      ),
    },
  ];
  return (
    <ProTable
      columns={weekPlanColumns}
      dataSource={getMyStuWeekPlan?.data || []}
      rowKey="id"
      pagination={{
        showQuickJumper: true,
      }}
      dateFormatter="string"
      headerTitle="周计划列表"
      options={false}
      search={false}
      // onSubmit={(e) => getUnderStuTask.run(e)}
      // onReset={() => getUnderStuTask.run()}
    />
  );
};
